#include "queue.h"
#include <stdio.h>

node* pop(list* lst) {

	if(lst->length == 0){
		printf("called 'pop' on list with no nodes\n");
		exit(1);
	}

	node* popped = lst->head;
	lst->head = popped->next;
	lst->length--;
	return popped;
}

node* rm(list* lst, int index){

	if(lst->length <= index){
		printf("list does not have that many elements, cannot remove");
		exit(1);
	}

	if(index == 0)
		return pop(lst);
	else{
		int i;
		node* n = lst->head;
		for(i = 0; i < index-1; i++){
			n = n->next;
		}

		node* rm = n->next; // node to be removed
		n->next = rm->next;

		if(index == lst->length-1)
			lst->tail = n;

		lst->length--;
		return rm;
	}



}

void cycle(list* lst){
	if(lst->length > 1){
		append(lst, 0,  pop(lst));
	}
}

/*
 * Appends either an existing node to lst, or creates
 * a node from controlBlock to append to lst. You should
 * only specify one of the two possible types, and the
 * other should be 0.
 */
void append(list* lst, pcb* controlBlock, node* n) {

	if(n){

		if (lst->length == 0) {

			lst->head = n;
			lst->tail = n;

		} else {
			node* oldTail = lst->tail;

			oldTail->next = n;
			n->next = 0;

			lst->tail = n;
		}
	}else if(controlBlock){
		node* newNode = (node*) malloc(sizeof(node));
		newNode->data = controlBlock;

		if (lst->length == 0) {

			lst->head = newNode;
			lst->tail = newNode;

		} else {
			node* oldTail = lst->tail;

			oldTail->next = newNode;
			newNode->next = 0;

			lst->tail = newNode;
		}
	}else{
		printf("Need to specify either a node or pcb\n");
		exit(1);
	}



	lst->length++;
}

void printList(list* lst){

	printf("%i processes found\n",lst->length);

	node* n = lst->head;
	int i;
	for(i = 0; i < lst->length; i++){
		printPCB(n->data);
		n = n->next;
	}
}

void printPCB(pcb* block){
	printf("R   :    %s        ",block->R);
	printf("SP  :    %s        ",block->SP);
	printf("IC  :    %s\n",block->IC);
	printf("BR  :    %s        ",block->BR);
	printf("LR  :    %s\n",block->LR);
	printf("C   :    %c        ",block->C);
	printf("PID:   %s\n\n",block->PID);
}


